package com.itheima.stock.service.impl;

import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户service实现类
 *
 * @author songyang
 * @date 2024/12/13
 **/
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser getUserByUserName(String userName) {
        return sysUserMapper.getUserByUserName(userName);
    }

    @Override
    public R<LoginRespVo> login(LoginReqVo po) {
        // 非空校验
        if (ObjectUtils.isEmpty(po)
                || ObjectUtils.isEmpty(po.getUsername())
                || ObjectUtils.isEmpty(po.getPassword())) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //密码匹配
        SysUser userByUserName = sysUserMapper.getUserByUserName(po.getUsername());

        if (ObjectUtils.isEmpty(userByUserName)) {
            // 用户不存在
            return R.error(ResponseCode.ACCOUNT_NOT_EXISTS.getMessage());
        }
        if (!passwordEncoder.matches(po.getPassword(), userByUserName.getPassword())) {
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        // 返回
        LoginRespVo result = new LoginRespVo();
        BeanUtils.copyProperties(userByUserName, result);
        return R.ok(result);
    }
}
